﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using Library.WebControls.SimpleDateEdit;
namespace Library.WebControls.SimpleGridView {
	/// <summary>
	/// Date grid column
	/// </summary>
	//[ParseChildren(true, "EditDateEdit")]
	public class SpGvDateColumn : SpGvBaseColumn {
		/// <summary>
		/// Create date grid column instance
		/// </summary>
		public SpGvDateColumn() {
			ContentStyle.HorizontalAlign = HorizontalAlign.Center;
			EditValueMode = EditValueMode.Attribute;
			FieldType = DataFieldType.Date;

			EditDateEdit = new EditTextEdit(this);
			EditDateEdit.Width = new Unit("100%");
		}
		/// <summary>
		/// Get column type
		/// </summary>
		public override GridColumnType ColumnType {
			get { return GridColumnType.DateEdit; }
		}

		///<summary>
		/// Date edit control
		///</summary>
		[PersistenceMode(PersistenceMode.InnerProperty)]
		[MergableProperty(false)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
		public SpDateEdit EditDateEdit { get; private set; }

		internal override BaseControl CreateClientEditControl() {
			return EditDateEdit;
		}
		private class EditTextEdit : SpDateEdit {
			private readonly SpGvBaseColumn _column;
			public EditTextEdit(SpGvBaseColumn column) {
				_column = column;
			}

			public override bool Visible {
				get { return _column.Visible; }
				set {

				}
			}
		}



		

		protected override string GetValueFromObject(object value) {
			if (value == null) return String.Empty;
			try {
				var date = Convert.ToDateTime(value);
				return String.Format("{0}|{1}|{2}", date.Year, date.Month - 1, date.Day);
			} catch (Exception) {
				return String.Empty;
			}
		}

		protected override object GetValuePostedFromClientOnEditMode() {
			if (EditValuePostedFromClientOnEditMode == null) return null;
			try {
				return DateTime.ParseExact(EditValuePostedFromClientOnEditMode, "yyyyMMdd",
																	 System.Threading.Thread.CurrentThread.CurrentUICulture);
			} catch {
				return null;
			}
		}
	}
}
